// hooks/project.tsx
"use client"

import { useState, useEffect, useCallback } from 'react'
import { ProjectAPI, ProjectDataTransformer } from '@/lib/projectapi'
import { useAuth } from '@/hooks/useAuth'
import type { 
  Project, 
  NewProjectForm, 
  ProjectStatus,
  ProjectListResponse
} from '@/types/project'

/**
 * 项目验证工具类
 */
class ProjectValidator {
  static validateForm(formData: NewProjectForm): Partial<Record<keyof NewProjectForm, string>> {
    const errors: Partial<Record<keyof NewProjectForm, string>> = {}

    if (!formData.name.trim()) {
      errors.name = '项目名称不能为空'
    }

    if (!formData.start_date) {
      errors.start_date = '开始日期不能为空'
    }

    if (!formData.end_date) {
      errors.end_date = '结束日期不能为空'
    }

    if (formData.budget && formData.budget.trim() !== '' && parseFloat(formData.budget) < 0) {
      errors.budget = '预算金额不能为负数'
    }

    if (formData.start_date && formData.end_date && formData.start_date > formData.end_date) {
      errors.end_date = '结束日期不能早于开始日期'
    }

    return errors
  }

  static hasRequiredFields(formData: NewProjectForm): boolean {
    return !!(formData.name.trim() && 
             formData.start_date && 
             formData.end_date)
  }
}

/**
 * 项目管理 Hook
 * 根据用户权限提供不同的功能：
 * - 实验室用户：完整的CRUD权限
 * - 实验室成员：只能查看本实验室的项目
 */
export function useProjects() {
  const { user, isAuthenticated } = useAuth()
  const [projects, setProjects] = useState<Project[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)

  // 用户权限检查
  const isLaboratoryUser = user?.user_type === 'laboratory'
  const canCreateProject = isLaboratoryUser
  const canEditProject = isLaboratoryUser
  const canDeleteProject = isLaboratoryUser

  /**
   * 加载项目列表
   */
  const fetchProjects = useCallback(async (filters?: {
    status?: string
    crop_type?: string
    search?: string
  }) => {
    if (!isAuthenticated) return

    try {
      setLoading(true)
      setError(null)
      
      const response: ProjectListResponse = await ProjectAPI.getProjects(filters)
      
      // 如果是实验室成员，只显示本实验室的项目
      let filteredProjects = Array.isArray(response.projects) ? response.projects : []
      if (!isLaboratoryUser && user?.laboratory_name) {
        // 注意：这里使用 laboratory_name 进行过滤
        // 如果后端返回的项目数据中有 laboratory_name 字段，使用该字段过滤
        filteredProjects = filteredProjects.filter(project => 
          (project as any).laboratory_name === user.laboratory_name
        )
      }
      
      setProjects(filteredProjects)
    } catch (err: any) {
      console.error('获取项目列表失败:', err)
      setError(err.message || '获取项目列表失败')
      setProjects([])
    } finally {
      setLoading(false)
    }
  }, [isAuthenticated, isLaboratoryUser, user?.laboratory])

  /**
   * 创建新项目
   */
  const createProject = useCallback(async (projectForm: NewProjectForm): Promise<{
    success: boolean
    message?: string
    project?: Project
  }> => {
    if (!canCreateProject) {
      return { success: false, message: '您没有权限创建项目' }
    }

    try {
      setLoading(true)
      setError(null)

      // 验证必填字段
      if (!ProjectValidator.hasRequiredFields(projectForm)) {
        return { success: false, message: '请填写所有必填字段' }
      }

      // 转换表单数据为 API 请求格式
      const requestData = ProjectDataTransformer.formToRequest(projectForm)

      const response = await ProjectAPI.createProject(requestData as any)
      
      // 刷新项目列表
      await fetchProjects()
      
      return { 
        success: true, 
        message: '项目创建成功',
        project: response.project
      }
    } catch (err: any) {
      console.error('创建项目失败:', err)
      const message = err.message || '创建项目失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canCreateProject, fetchProjects])

  /**
   * 更新项目
   */
  const updateProject = useCallback(async (
    projectId: string, 
    projectForm: NewProjectForm
  ): Promise<{
    success: boolean
    message?: string
    project?: Project
  }> => {
    if (!canEditProject) {
      return { success: false, message: '您没有权限编辑项目' }
    }

    try {
      setLoading(true)
      setError(null)

      // 验证必填字段
      if (!ProjectValidator.hasRequiredFields(projectForm)) {
        return { success: false, message: '请填写所有必填字段' }
      }

      // 转换表单数据为 API 请求格式
      const requestData = ProjectDataTransformer.formToRequest(projectForm)

      const response = await ProjectAPI.updateProject(projectId, requestData as any)
      
      // 更新本地项目列表
      setProjects(prev => Array.isArray(prev) ? prev.map(p => 
        p.id === projectId ? response.project : p
      ) : [])
      
      return { 
        success: true, 
        message: '项目更新成功',
        project: response.project
      }
    } catch (err: any) {
      console.error('更新项目失败:', err)
      const message = err.message || '更新项目失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditProject])

  /**
   * 删除项目
   */
  const deleteProject = useCallback(async (projectId: string): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canDeleteProject) {
      return { success: false, message: '您没有权限删除项目' }
    }

    try {
      setLoading(true)
      setError(null)

      await ProjectAPI.deleteProject(projectId)
      
      // 从本地列表中移除
      setProjects(prev => Array.isArray(prev) ? prev.filter(p => p.id !== projectId) : [])
      
      return { success: true, message: '项目删除成功' }
    } catch (err: any) {
      console.error('删除项目失败:', err)
      const message = err.message || '删除项目失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canDeleteProject])

  /**
   * 更新项目状态
   */
  const updateProjectStatus = useCallback(async (
    projectId: string, 
    status: ProjectStatus
  ): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canEditProject) {
      return { success: false, message: '您没有权限修改项目状态' }
    }

    try {
      setLoading(true)
      setError(null)

      const response = await ProjectAPI.updateProject(projectId, { status })
      
      // 更新本地项目列表
      setProjects(prev => prev.map(p => 
        p.id === projectId ? response.project : p
      ))
      
      return { success: true, message: '项目状态更新成功' }
    } catch (err: any) {
      console.error('更新项目状态失败:', err)
      const message = err.message || '更新项目状态失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditProject])

  /**
   * 上传项目附件
   */
  const uploadAttachments = useCallback(async (
    projectId: string, 
    files: File[]
  ): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canEditProject) {
      return { success: false, message: '您没有权限上传附件' }
    }

    try {
      setLoading(true)
      setError(null)

      await ProjectAPI.uploadAttachments(projectId, files)
      
      // 刷新项目列表以获取最新的附件信息
      await fetchProjects()
      
      return { success: true, message: '附件上传成功' }
    } catch (err: any) {
      console.error('上传附件失败:', err)
      const message = err.message || '上传附件失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditProject, fetchProjects])

  /**
   * 删除项目附件
   */
  const deleteAttachment = useCallback(async (
    projectId: string, 
    attachmentId: string
  ): Promise<{
    success: boolean
    message?: string
  }> => {
    if (!canEditProject) {
      return { success: false, message: '您没有权限删除附件' }
    }

    try {
      setLoading(true)
      setError(null)

      await ProjectAPI.deleteAttachment(projectId, attachmentId)
      
      // 刷新项目列表以获取最新的附件信息
      await fetchProjects()
      
      return { success: true, message: '附件删除成功' }
    } catch (err: any) {
      console.error('删除附件失败:', err)
      const message = err.message || '删除附件失败'
      setError(message)
      return { success: false, message }
    } finally {
      setLoading(false)
    }
  }, [canEditProject, fetchProjects])

  /**
   * 下载项目附件
   */
  const downloadAttachment = useCallback(async (
    projectId: string, 
    attachmentId: string,
    fileName: string
  ) => {
    try {
      await ProjectAPI.downloadAttachment(projectId, attachmentId, fileName)
    } catch (err: any) {
      console.error('下载附件失败:', err)
      setError(err.message || '下载附件失败')
    }
  }, [])

  // 初始化加载项目
  useEffect(() => {
    if (isAuthenticated) {
      fetchProjects()
    }
  }, [isAuthenticated, fetchProjects])

  return {
    // 数据
    projects,
    loading,
    error,
    
    // 权限
    canCreateProject,
    canEditProject,
    canDeleteProject,
    isLaboratoryUser,
    
    // 方法
    fetchProjects,
    createProject,
    updateProject,
    deleteProject,
    updateProjectStatus,
    uploadAttachments,
    deleteAttachment,
    downloadAttachment,
    
    // 清除错误
    clearError: () => setError(null)
  }
}

/**
 * 项目表单管理 Hook
 */
export function useProjectForm(initialProject?: Project) {
  const [formData, setFormData] = useState<NewProjectForm>({
    name: initialProject?.name || '',
    description: initialProject?.description || '',
    crop_type: initialProject?.crop_type || '',
    location: initialProject?.location || '',
    start_date: initialProject?.start_date || '',
    end_date: initialProject?.end_date || '',
    manager: initialProject?.manager || '',
    status: initialProject?.status,
    budget: initialProject?.budget ? initialProject.budget.toString() : '',
    objectives: initialProject?.objectives ? initialProject.objectives.join('\n') : '',
    attachments: []
  })

  const [errors, setErrors] = useState<Partial<Record<keyof NewProjectForm, string>>>({})

  /**
   * 更新表单字段
   */
  const updateField = useCallback((field: keyof NewProjectForm, value: any) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
    
    // 清除该字段的错误
    if (errors[field]) {
      setErrors(prev => ({
        ...prev,
        [field]: undefined
      }))
    }
  }, [errors])

  /**
   * 添加附件
   */
  const addAttachments = useCallback((files: File[]) => {
    setFormData(prev => ({
      ...prev,
      attachments: [...prev.attachments, ...files]
    }))
  }, [])

  /**
   * 移除附件
   */
  const removeAttachment = useCallback((index: number) => {
    setFormData(prev => ({
      ...prev,
      attachments: prev.attachments.filter((_, i) => i !== index)
    }))
  }, [])

  /**
   * 验证表单
   */
  const validateForm = useCallback((): boolean => {
    const newErrors = ProjectValidator.validateForm(formData)
    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }, [formData])

  /**
   * 重置表单
   */
  const resetForm = useCallback(() => {
    setFormData({
      name: '',
      description: '',
      crop_type: '',
      location: '',
      start_date: '',
      end_date: '',
      manager: '',
      status: undefined,
      budget: '',
      objectives: '',
      attachments: []
    })
    setErrors({})
  }, [])

  return {
    formData,
    errors,
    updateField,
    addAttachments,
    removeAttachment,
    validateForm,
    resetForm,
    setFormData
  }
}